package com.vv.tools.common.util;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vv.tools.common.support.BasePage;

import java.util.function.Function;
import java.util.stream.Collectors;

import lombok.Getter;
import lombok.Setter;

/**
 * 分页插件
 */
@Getter
@Setter
public class PageUtil<T> {

    private Long pageIndex;

    private Long pageSize;

    private BaseMapper<T> baseMapper;

    private Page<T> page;

    public PageUtil() {
        this.pageIndex = 1L;
        this.pageSize = 10L;
    }

    public PageUtil(Long pageIndex, Long pageSize) {
        this.pageIndex = pageIndex;
        this.pageSize = pageSize;
    }

    public PageUtil(BasePage basePage) {
        this.pageIndex = Long.valueOf(basePage.getPageIndex());
        this.pageSize = Long.valueOf(basePage.getPageSize());
    }

    public <I extends BaseMapper<T>> PageUtil<T> of(I baseMapper) {
        this.baseMapper = baseMapper;
        return this;
    }

    public PageUtil<T> query(Wrapper<T> queryWrapper) {
        Page<T> queryPage = new Page<>();
        queryPage.setCurrent(pageIndex);
        queryPage.setSize(pageSize);
        this.page = baseMapper.selectPage(queryPage, queryWrapper);
        return this;
    }

    public <R> Page<R> mapper(Function<T, R> function) {
        Page<R> p = new Page<>();
        p.setSize(page.getSize());
        p.setCurrent(page.getCurrent());
        p.setPages(page.getPages());
        p.setTotal(page.getTotal());
        p.setRecords(page.getRecords().stream().map(function).collect(Collectors.toList()));
        return p;
    }

}
